package ar.edu.unlu.sistemas.p2p.business.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ar.edu.unlu.sistemas.p2p.android.sql.IndexOpenHelper;
import ar.edu.unlu.sistemas.p2p.business.exception.MovirdroidException;
import ar.edu.unlu.sistemas.p2p.business.exception.MovirdroidExceptionMessages;

public class StringUtils {
	
	public static String convertToSQLSet(Collection<String> coll) {
		return convertToSQLSet(coll.toArray());
	}
	
	public static String convertToSQLSet(Object[] arr) {
		StringBuffer str = new StringBuffer();
		str.append("(");
		String temp;
		for (int i = 0; i<arr.length;i++){
			temp = (String) arr[i];
			str.append(temp+",");
		}
		str.deleteCharAt(str.length()-1);
		str.append(")");
		return str.toString();
	}
	
	public static String convertToInterrogativeSQLSet(int length) {
		StringBuffer str = new StringBuffer();
		str.append("(");
		for (int i = 0; i<length;i++) {
			str.append("?,");
		}
		str.deleteCharAt(str.length()-1);
		str.append(")");
		return str.toString();
	}
	
	public static String[] fromObjArr2StrArr(Object[] objArr) {
		String [] strArr = new String[objArr.length];
		for (int i=0;i<objArr.length;i++) {
			strArr[i] = (String)objArr[i];
		}
		return strArr;
	}
	
	public static boolean esStringVacioONull(String str) {
		return (str == null) || ("".equals(str));
	}
	
	public static String fromFloatToString(Float num) {
		return num != null ? num.toString() : "";
	}
	
	public static String parseMacAddress(String macAddr) {
		String[] macBytes = macAddr.split(":");
		StringBuffer sb = new StringBuffer();
		for (int i = 0;i<macBytes.length;i++) {
			sb.append(macBytes[i]);
		}
		return sb.toString();
	}
	
	/**
	 * Recibe una linea de un archivo de texto y retorna un array con los términos que se encontraron
	 * dentro de ésta
	 * 
	 * @param line
	 * @return Array de los términos en la línea de texto
	 * @throws UnsupportedEncodingException
	 */
	public static String[] tokenize(String line) throws UnsupportedEncodingException{
		 line = line.toLowerCase();
		 line = line.replaceAll("[óÓòÒôôöÖõÕ]", "o");
		 line = line.replaceAll("[íÍìÌîÎïÏ]", "i");
		 line = line.replaceAll("[áÁàÀâÂÄåÅãÃä]", "a");
		 line = line.replaceAll("[éÉèÈÊêëË]", "e");
		 line = line.replaceAll("[úüÚÜùÙûÛ]", "u");
		 line = line.replaceAll("ñ", "n");
		 line = line.replaceAll("\\W", " ");
		 line = line.replaceAll("[1234567890]"," ");
		 return line.split("\\s+");
	}
	
	public static String processLogicalExpression(String expr) throws MovirdroidException {
		
		String pattern1 = "((NOT\\s){0,1}\\w+(\\s(AND|OR){1}\\s(NOT\\s){0,1}\\w+)*)+";
		String pattern2 = "((\\(\\s{0,1}"+pattern1+"\\s{0,1}\\)|"+pattern1+")+(\\s(AND|OR){1}\\s(\\(\\s{0,1}"+pattern1+"\\s{0,1}\\)|"+pattern1+"))*)+";
		
		// Compile and use regular expression
		Pattern pattern;
		Matcher matcher;
		boolean matchFound = expr.matches(pattern2);
		if (matchFound) {
			expr = expr.replace("OR", "+");
			expr = expr.replace("AND", "*");
			String acStr = new String(expr);
			Collection<String> matches = new ArrayList<String>();
			String groupStr;
			while (matchFound) {
				pattern = Pattern.compile("(\\w+)");
				matcher = pattern.matcher(acStr);
				matchFound = matcher.find();
				if (matchFound) {
					groupStr = matcher.group(0);
					matches.add(groupStr);
					acStr=acStr.replace(groupStr, "%");
				}
			}
			for (Iterator<String> i = matches.iterator(); i.hasNext(); ) {
				groupStr = i.next();
				expr = expr.replace(groupStr, "ifnull((SELECT "+IndexOpenHelper.TF_VALUE+" FROM "+IndexOpenHelper.TF_TABLE_NAME+" WHERE "+IndexOpenHelper.TF_WORD+" = (SELECT "+IndexOpenHelper.WORD_ID+" FROM "+IndexOpenHelper.WORD_TABLE_NAME+" WHERE "+IndexOpenHelper.WORD_KEY+" = '"+groupStr+"') AND "+IndexOpenHelper.TF_DOC+" = d."+IndexOpenHelper.DOC_ID+"),0)");
			}
		} else {
			throw new MovirdroidException(MovirdroidExceptionMessages.BAD_LOGICAL_EXPR);
		}
		return expr;
	}

}
